<template>
  <div class="bg-white sticky top-0 left-0 z-10 dark:bg-zinc-900 duration-500">
    <ul
      class="relative flex overflow-x-auto p-1 text-xs text-zinc-600 overflow-hidden"
      ref="ulTarget"
    >
      <!-- category item -->
      <li
        class="shrink-0 px-1.5 py-0.5 z-10 duration-200 last:mr-4"
        v-for="(item, index) in $store.getters.categorys"
        :key="item.id"
        :ref="setItemRef"
        @click="onItemClick(item)"
        :class="{
          'text-zinc-100': $store.getters.currentCategoryIndex === index
        }"
      >
        {{ item.name }}
      </li>

      <!-- 滑块 -->
      <li
        class="absolute h-[22px] bg-zinc-900 rounded-lg duration-200 dark:bg-zinc-800"
        :style="sliderStyle"
        ref="sliderTarget"
      ></li>

      <!-- 汉堡包按钮 -->
      <li
        class="fixed z-50 top-0 right-[-1px] h-4 px-1 flex items-center bg-white shadow-l-white dark:bg-zinc-900 dark:shadow-l-zin"
        @click="isOpenPopup = true"
      >
        <m-svg-icon class="w-1.5 h-1.5" name="hamburger"></m-svg-icon>
      </li>
    </ul>

    <!-- 弹层 -->
    <m-popup v-model="isOpenPopup">
      <menu-vue @onItemClick="onItemClick" />
    </m-popup>
  </div>
</template>

<script setup>
import { ref, onBeforeUpdate, watch, nextTick } from 'vue'
import { useStore } from 'vuex'
import { useScroll } from '@vueuse/core'
import menuVue from '../../menu/index.vue'

const store = useStore()

const isOpenPopup = ref(false)

// 处理列表item的ref
let ItemRefs = []
const setItemRef = (el) => {
  ItemRefs.push(el)
}
onBeforeUpdate(() => {
  ItemRefs = []
})

const sliderStyle = ref({
  width: '52px',
  transform: 'translateX(0)'
})

// 获取 ul 元素，以计算偏移位置
const ulTarget = ref(null)
const { x: ulScrollLeft } = useScroll(ulTarget)

watch(
  () => store.getters.currentCategoryIndex,
  (val) => {
    nextTick(() => {
      // 获取选中元素的 left、width
      const { left, width } = ItemRefs[val].getBoundingClientRect()
      // 为 sliderStyle 设置属性
      sliderStyle.value = {
        width: width + 'px',
        // ul 横向滚动位置 + 当前元素的 left 偏移量 - 10px padding
        transform: `translateX(${ulScrollLeft.value + left - 10 + 'px'})`
      }
    })
  },
  {
    immediate: true
  }
)

// 处理列表item的点击
const onItemClick = (item) => {
  store.commit('app/changeCurrentCategory', item)
  isOpenPopup.value = false
}
</script>
